﻿using System.Collections.Generic;
using System.Web.Mvc;
using JSC.Portal.Services;
using JSC.Core;
using JSC.Portal.Entities;
using JSC.Portal.Web.Models;
using JSC.Portal.Web.Filters;
using NHibernate;
using JSC.Data.NHibernate;
using System.Web;
using System.Linq;

namespace JSC.Portal.Web.Controllers
{
    [Authorize(Roles = "Administrator,SiteAdministrator")]
    [HandleError]
    public class PortalPageDesignerController : Controller
    {
        [Compress]
        public ActionResult Design(int id)
        {
            IPortalPageService svc = FacadeFactory.CreateFacade<IPortalPageService>();
            PortalPage page = svc.GetById(id, false);

            string phhs = string.Empty;
            string path = VirtualPathUtility.Combine(page.Template.Path, page.Template.ControlName);
            path = Server.MapPath(path);
            IList<string> placeholders = svc.GetTemplatePlaceholders(path);
            placeholders.ForEach<string>(delegate(string ph)
            {
                if (!string.IsNullOrEmpty(phhs))
                    phhs += ", ";
                phhs += string.Format("'#{0}'", ph);
            });


            DesignPageViewData data = new DesignPageViewData(page, phhs, placeholders[0]);
            data.Initialize();

            IModuleTypeService moduleTypeService = FacadeFactory.CreateFacade<IModuleTypeService>();
            this.ViewData["ModuleTypes"] = new SelectList(moduleTypeService.GetAll(), "Id", "Name");

            return View("Design", data);
        }

        [JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignDTO>))]
        public JsonResult SaveOrUpdate(int id, List<PageDesignDTO> widgets)
        {
            using (ITransaction trans = NHibernateSession.Current.BeginTransaction())
            {
                ISectionService sSvc = FacadeFactory.CreateFacade<ISectionService>();
                IPortalPageService svc = FacadeFactory.CreateFacade<IPortalPageService>();
                IModuleTypeService mtSvc = FacadeFactory.CreateFacade<IModuleTypeService>();
                PortalPage page = svc.GetById(id, false);

                for(int i = page.Sections.Count - 1; i >= 0; i--)
                {
                    Section s = page.Sections[i];
                    PageDesignDTO dto = widgets.SingleOrDefault(w => w.SectionId.HasValue && w.SectionId.Value == s.Id);
                    if (dto != null)
                    {
                        s.Placeholder = dto.Placeholder;
                        s.Position = dto.Position;
                    }
                    else
                    {
                        /// 
                        /// Before deleting you must decouple yourself from the Page
                        /// 
                        page.Sections.Remove(s);
                        sSvc.Delete(s);
                    }
                }
                foreach(PageDesignDTO newDto in widgets)
                {
                    if (newDto.SectionId.HasValue)
                        continue;
                    
                    ModuleType mt = mtSvc.GetById(newDto.ModuleTypeId, false);
                    Section s = sSvc.GetNewSection(id);
                    s.Name = string.Format("dcmt_{0}", mt.Name);
                    s.ModuleType = mt;
                    s.Placeholder = newDto.Placeholder;
                    s.Position = newDto.Position;
                    page.Sections.Add(s);

                    newDto.ModulePropertiesValues.ForEach(delegate(ModulePropertyValueDTO dto)
                    {
                        ModuleProperty mp = s.ModuleType.ModuleProperties.Single(x => x.Name == dto.Name);
                        SectionModulePropertyValue smpv = new SectionModulePropertyValue() { ModuleProperty = mp, Section = s, Value = dto.Value };
                        s.Settings.Add(smpv);
                    });
                }

                svc.SaveOrUpdate(page);
                trans.Commit();
                return Json(new { Url = Url.Action("Design", new { id = id }) });
            }
        }

        public ActionResult AddModuleDesignControl()
        {
            IModuleTypeService moduleTypeService = FacadeFactory.CreateFacade<IModuleTypeService>();
            this.ViewData["ModuleTypes"] = new SelectList(moduleTypeService.GetAll(), "Id", "Name");
            return PartialView();
        }

        public ActionResult GetModuleProperties(int moduleTypeId)
        {
            IModuleTypeService moduleTypeService = FacadeFactory.CreateFacade<IModuleTypeService>();
            ModuleType mt = moduleTypeService.GetById(moduleTypeId, false);

            IList<SectionModulePropertyValue> result = new List<SectionModulePropertyValue>();
            foreach (ModuleProperty mp in mt.ModuleProperties)
            {
                SectionModulePropertyValue smpv = new SectionModulePropertyValue();
                smpv.ModuleProperty = mp;
                //smpv.Section = s;
                result.Add(smpv);
            }

            return PartialView("ModulePropertiesEditControl", result);
        }
    }
}
